package com.xiashitech.apiservice.util;

import java.io.*;
import java.util.*;
import java.math.*;
import java.nio.charset.StandardCharsets;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import lombok.var;

import com.alibaba.fastjson.*;
import com.alibaba.fastjson.parser.Feature;
import com.google.common.collect.Lists;

import org.springframework.web.multipart.MultipartFile;

public class JsonIoUtil {
    private static final Log log = LogFactory.get();

    public static JSONArray parseJson(MultipartFile file) {
        JSONArray result = new JSONArray();
        try {
            byte[] bytes = file.getBytes();
            String fileContent = new String(bytes, StandardCharsets.UTF_8);
            JSONValidator validator = JSONValidator.from(fileContent);
            if (JSONValidator.Type.Array == validator.getType()) {
                var items = (JSONArray) JSON.parse(fileContent, Feature.OrderedField);
                result = formatInData(items);
            }
        } catch (IOException e) {
            log.error(e);
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 格式化json
     * 
     * @param jsonArray
     * @return
     */
    public static JSONArray formatInData(JSONArray jsonArray) {
        var result = new JSONArray();
        for (var i = 0; i < jsonArray.size(); i++) {
            var item = jsonArray.get(i);
            if (item instanceof JSONObject) {
                var jo = (JSONObject) item;
                var values = Lists.newArrayList();
                for (var key : jo.keySet()) {
                    var value = jo.get(key);
                    if (value instanceof Number) {
                        var scientificNumber = String.valueOf(value).replace("E", "e");
                        var stringValue = new BigDecimal(scientificNumber).toPlainString();
                        values.add(stringValue.replaceAll("\\.0+$", ""));
                    } else if (value == null) {
                    } else {
                        values.add(value.toString());
                    }
                }
                result.add(values);
            }
        }
        return result;
    }

    public static List<String> getKeysOfObjectWithMostKeys(JSONArray data) {
        List<String> result = Lists.newArrayList();
        var mostKeysObject = new JSONObject();
        int maxKeys = Integer.MIN_VALUE;
        var item1 = data.get(0);
        if (item1 instanceof List)
            return result;
        if (item1 instanceof Map) {
            for (var obj : data) {
                var item = JSONObject.parseObject(JSON.toJSONString(obj), Feature.OrderedField);
                if (item.size() > maxKeys) {
                    mostKeysObject = item;
                    maxKeys = item.size();
                }
            }
        }
        if (mostKeysObject.isEmpty())
            return result;
        return new ArrayList<>(mostKeysObject.keySet());
    }
}
